<?php

namespace app\yy\services;
use app\yy\model\Currency as CurrencyModel;

class Currency extends BaseService
{
    public function index()
    {
        $currencyArray = $this->getCurrencyArray();

        if (!$currencyArray){
            echo '更新汇率失败!';die;
        }

        $all_currency = CurrencyModel::order('id')->select();

        foreach ($all_currency as $cu){
            if(isset($currencyArray[$cu['name']])){
                $rate = $currencyArray[$cu['name']];
                $up_data = [
                    'rate'  =>  $rate,
                    'update_time'  =>  time(),
                ];
                CurrencyModel::where('id',$cu['id'])->update($up_data);
            }else{
                echo $cu['name'].'货币汇率更新失败!';
            }
        }
        echo '货币汇率更新!';die;

    }

    function getCurrencyArray($base = 'USD')
    {
        $currencyCodeArray = array(
            '美元'=>'USD',
            '欧元'=>'EUR',
            '英镑'=>'GBP',
            '加拿大元'=>'CAD',
            '澳大利亚元'=>'AUD',
            '日元'=>'JPY',
            '港币'=>'HKD',
            '泰国铢'=>'THB',
            '新加坡元'=>'SGD',
            '瑞士法郎'=>'CHF',
            '丹麦克朗'=>'DKK',
            '澳门元'=>'MOP',
            '林吉特'=>'MYR',
            '挪威克朗'=>'NOK',
            '新西兰元'=>'NZD',
            '菲律宾比索'=>'PHP',
            '卢布'=>'RUB',
            '瑞典克朗'=>'SEK',
            '新台币'=>'TWD',
            '巴西雷亚尔'=>'BRL',
            '韩国元'=>'KRW',
            '南非兰特'=>'ZAR',
        );
        $url = 'http://web.juhe.cn:8080/finance/exchange/rmbquot?key=b6ec4ac30f5557ee6cd6c651bda41912';
        $currenciesContent = @json_decode(file_get_contents($url));
        $currencyArray = array();


        if(!empty($currenciesContent->result)){
            foreach ($currenciesContent->result[0] as $line) {
                $currencyArray[$currencyCodeArray[$line->name]] = $line->bankConversionPri/100;
            }
            foreach ($currencyArray as $key=>$currency) {
                $rate[$key] = (string)(float)($currencyArray[$key]/$currencyArray[$base]);
                if($key==$base){
                    $rate[$key] = 1;
                }
            }
            return $rate;
        }else{
            return false;
        }
    }
}